<template lang="pug">
  ul
    li(v-for="(color, idx) in colors") 
      .color(:style="{backgroundColor: color.hex}")
      span {{ `${color.name}`  }}

  form(@submit="handleSubmit")
    label  hex:
      input(type="test" v-model="formData.hex" style="width: 4rem;")
    label  r:
      input(type="number" v-model.number="formData.rgb.r" )
    label  g:
      input(type="number" v-model.number="formData.rgb.g" )
    label  b:
      input(type="number" v-model.number="formData.rgb.b" )
    br
    label  c:
      input(type="number" v-model.number="formData.cmyk.c" )
    label  m:
      input(type="number" v-model.number="formData.cmyk.m" )
    label  y:
      input(type="number" v-model.number="formData.cmyk.y" )
    label  k:
      input(type="number" v-model.number="formData.cmyk.k" )
    br
    input(type="text" v-model.trim="formData.name" placeholder="name" style="width: 8rem;")
    button(type="submit"  :disabled="!formData.name") create color
    button(type="button" @click="resetFormData") Reset

</template>

<script setup>
import { ref, onMounted, watch, inject } from 'vue'
import api from '../apis/api'
import { hexToRgb, rgbToHex } from '../utils/color-convert'
const mainBrandId = inject('mainBrandId')
const colors = inject('colors')

const formData = ref({
  name: '',
  brandId: mainBrandId,
  hex: '#',
  rgb: { r: 0, g: 0, b: 0 },
  cmyk: { c: 0, m: 0, y: 0, k: 0 },
  ral: { r: undefined, a: undefined, l: undefined },
  pantone: '',
})

const formDataString = JSON.stringify(formData.value)
const initialFormData = { ...JSON.parse(formDataString) };
const resetFormData = () => {
  for (let key in initialFormData) {
    formData.value[key] = initialFormData[key];
  }
};

async function handleSubmit(event) {
  event.preventDefault();
  if (!formData.value.name) { return }
  await api.post('colors', { ...formData.value, rgb: { ...formData.value.rgb } })
  resetFormData()
}

</script>



<style scoped>
li {
  display: inline-block;
  padding: 0.2rem;
}

li div {
  width: 3rem;
  height: 3rem;
  border: 1px solid #ccc;
}

li span {
  font-size: 0.8rem;
}

input {
  width: 3rem;
}
</style>
